package ai.mspbots.test.service;

import ai.mspbots.test.dto.ApiKeyDTO;
import ai.mspbots.test.entity.ApiKeyEntity;
import ai.mspbots.test.mapper.ApiKeyEntityMapper;
import ai.mspbots.test.mapper.SysDictDataMapper;
import ai.mspbots.test.util.OpenAIApiValidator;
import ai.mspbots.test.CryptoUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * API密钥管理服务
 * 
 * @author mspbots
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class ApiKeyManagementService {

    private final SysDictDataMapper sysDictDataMapper;
    private final OpenAIApiValidator openAIApiValidator;
    private final ApiKeyEntityMapper apiKeyEntityMapper;
    private final ObjectMapper objectMapper;

    /**
     * 验证API密钥有效性
     */
    public void validateApiKey() {
        List<ApiKeyDTO> apiKeyList = sysDictDataMapper.selectApiKey();
        List<ApiKeyDTO> decodes = apiKeyList.stream()
                .peek(item -> {
                    String key = item.getApiKey();
                    if (key != null) {
                        String decodeTarget = CryptoUtil.decodeTarget(key);
                        item.setApiKey(decodeTarget);
                    }
                })
                .collect(Collectors.toList());

        decodes.forEach(item -> openAIApiValidator.isApiKeyValid(item));
    }

    /**
     * 加载所有API密钥
     */
    public List<ApiKeyEntity> loadApiKey() {
        LambdaQueryWrapper<ApiKeyEntity> wrapper = new LambdaQueryWrapper<>();
        List<ApiKeyEntity> apiKeyList = apiKeyEntityMapper.selectList(wrapper);
        log.info("加载到 {} 个API密钥", apiKeyList.size());
        return apiKeyList;
    }

    /**
     * 保存API密钥
     */
    public void saveApiKey(ApiKeyDTO apiKeyDTO) throws JsonProcessingException {
        ApiKeyEntity apiKeyEntity = ApiKeyEntity.covert(apiKeyDTO);
        JsonNode jsonNode = objectMapper.readTree("{\"model\":\"gpt-3.5-turbo\"}");
        apiKeyEntity.setModel(jsonNode);
        apiKeyEntityMapper.insert(apiKeyEntity);
        log.info("API密钥保存成功: {}", apiKeyEntity.getId());
    }
}
